extends Node2D
@onready var texture_rect: TextureRect = $TextureRect
@onready var mouse_click: AnimatedSprite2D = $AnimatedSprite2D
@onready var mVBoxContainer: VBoxContainer = $CanvasLayer/HSplitContainer/Control/VBoxContainer
@onready var position_label: Label = $CanvasLayer/HSplitContainer/Control/TextureRect/HBoxContainer/CenterContainer/Label
@onready var background_map: TextureRect = $BackgroundMap
@onready var main_scene: Node2D = $"."
@onready var player: Node2D = $Player
@onready var role: Node2D = $Role
@onready var camera_2d: Camera2D = $Role/Camera2D
@onready var dialog_box: TextureRect = $CanvasLayer/HSplitContainer/Control/DialogBox
@onready var grid_container: GridContainer = $CanvasLayer/HSplitContainer/Control/DialogBox/GridContainer
@onready var control: Control = $CanvasLayer/HSplitContainer/Control
@onready var fight: Control = $CanvasLayer/HSplitContainer/Control/Fight

@onready var h_split_container: HSplitContainer = $CanvasLayer/HSplitContainer
@onready var texture_rect_2: TextureRect = $CanvasLayer/HSplitContainer/Control/TextureRect2


#鼠标点击的坐标
var target_position = Vector2()
#当前角色面朝的方向
var current_direction: int = 2
#最小角度
var min_angle = PI / 8
#移动速度
var speed: int = 5
@onready var right_1: Area2D = $Test9
var map_name: String = "长安城"
var userInfo = StringUtil.read_file_to_Dic("res://config/UserInfo.json")
var door_array = []
var os_name = OS.get_name()
func load_map_and_npc(id: float) -> void:
	background_map.texture = load(ResourceUtil.load_map(id))
	var mapData = MapUtil.get_map_for_id(id)
	var doorArray = DoorUtil.get_door_for_ids(mapData["door"])
	for item in doorArray:
		var portal = preload("res://layout/Portal.tscn").instantiate()
		portal.position = Vector2(item["x"], item["y"])
		portal.add_to_group("door")
		portal.door_id = item["id"]
		background_map.add_child(portal)
		portal.connect("collision_transmit", Callable(self, "_collision_transmit"))
	var npcArray = NpcUtil.get_npc_for_ids(mapData["npc"])
	for item in npcArray:
		var npc = preload("res://layout/Npc.tscn").instantiate()
		npc.position = Vector2(item["x"], item["y"])
		npc.add_to_group("door")
		background_map.add_child(npc)
		npc.connect("click_npc", Callable(self, "_click_npc"))
		npc.setImage(item["id"])

func _ready() -> void:
	#if 'Android' == os_name:
		#print("这是Android设备")
		#control.size= Vector2(2400-387, 1080)
	#elif 'iOS' == os_name:
		#print("这是iOS设备")
	#elif 'Windows' == os_name:
		#print("这是桌面设备")
		#h_split_container.size= Vector2(2400-387, 1080)
		#control.size= Vector2(2400-387, 1080)
	#elif 'HTML5' == os_name:
		#print("这是在浏览器中运行")
	#var screen_size = DisplayServer.screen_get_size()
	#print("屏幕宽度: ", screen_size.x)
	#print("屏幕高度: ", screen_size.y)
	#加载地图
	load_map_and_npc(userInfo["map_id"])
	#加载玩家
	role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_8", userInfo["name"], true)
	role.position = Vector2(userInfo["map_x"], userInfo["map_y"])
	var mapData = MapUtil.get_map_for_id(userInfo["map_id"])
	camera_2d.limit_left = 0
	camera_2d.limit_top = 0
	camera_2d.limit_right = mapData["width"]
	camera_2d.limit_bottom = mapData["height"]
	fight.connect("hide_fight", Callable(self, "_hide_fight"))

func _physics_process(delta: float) -> void:
	if target_position.distance_to(global_position) > 0:
		var move_angle = role.global_position.angle_to_point(target_position)
		if move_angle == 0:
			if current_direction == 1:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_1", userInfo["name"], true)
			elif current_direction == 2:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_2", userInfo["name"], true)
			elif current_direction == 3:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_3", userInfo["name"], true)
			elif current_direction == 4:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_4", userInfo["name"], true)
			elif current_direction == 6:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_6", userInfo["name"], true)
			elif current_direction == 7:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_7", userInfo["name"], true)
			elif current_direction == 8:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_8", userInfo["name"], true)
			elif current_direction == 9:
				role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_9", userInfo["name"], true)
			return
		elif move_angle > min_angle * 5 and move_angle <= min_angle * 7:
			current_direction = 9
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_9", userInfo["name"], true)
		elif move_angle > min_angle * 3 and move_angle <= min_angle * 5:
			current_direction = 8
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_8", userInfo["name"], true)
		elif move_angle > min_angle and move_angle <= min_angle * 3:
			current_direction = 7
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_7", userInfo["name"], true)
		elif move_angle > min_angle * 7 or move_angle <= -min_angle * 7:
			current_direction = 6
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_6", userInfo["name"], true)
		elif move_angle < min_angle and move_angle > -min_angle:
			current_direction = 4
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_4", userInfo["name"], true)
		elif move_angle < -min_angle * 5 and move_angle >= -min_angle * 7:
			current_direction = 3
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_3", userInfo["name"], true)
		elif move_angle < -min_angle * 3 and move_angle >= -min_angle * 5:
			current_direction = 2
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_2", userInfo["name"], true)
		elif move_angle < -min_angle and move_angle >= -min_angle * 3:
			current_direction = 1
			role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "run_1", userInfo["name"], true)
		role.global_position = role.global_position.move_toward(target_position, speed)
		print(role.global_position)
		position_label.text = map_name + "  [" + str(int(role.position.x / 20)) + "," + str(int(role.position.y / 20)) + "]"


func _on_background_gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.is_pressed() and event.button_index == MouseButton.MOUSE_BUTTON_RIGHT:
			target_position = get_global_mouse_position()
			mouse_click.visible = true
			mouse_click.position = target_position
			mouse_click.stop()
			mouse_click.play()


func _on_animated_sprite_2d_animation_finished() -> void:
	mouse_click.visible = false


func _on_texture_button_pressed() -> void:
	ToastUtil.showToast(mVBoxContainer, "请输入角色名")


func _on_v_box_container_child_entered_tree(node: Node) -> void:
	await get_tree().create_timer(2.0).timeout
	mVBoxContainer.remove_child(node)



	
func _collision_transmit(position: int):
	for node in get_tree().get_nodes_in_group("door"):
		node.get_parent().remove_child(node)
		node.queue_free()
	var door = DoorUtil.get_door_for_id(position)
	background_map.texture = load(ResourceUtil.load_map(door["dest_id"]))
	role.setImage(ResourceUtil.load_animation(userInfo["skin"]), "stand_8", userInfo["name"], true)
	role.position = Vector2(door["dest_x"], door["dest_y"])
	target_position = Vector2(door["dest_x"], door["dest_y"])
	var mapData = MapUtil.get_map_for_id(door["dest_id"])
	position_label.text = mapData["name"] + "  [" + str(int(role.position.x / 20)) + "," + str(int(role.position.y / 20)) + "]"
	var doorArray = DoorUtil.get_door_for_ids(mapData["door"])
	for item in doorArray:
		var portal = preload("res://layout/Portal.tscn").instantiate()
		portal.position = Vector2(item["x"], item["y"])
		portal.add_to_group("door")
		portal.door_id = item["id"]
		background_map.add_child(portal)
		portal.connect("collision_transmit", Callable(self, "_collision_transmit"))
		
func _click_npc(id: int):
	var npc_data = NpcUtil.get_npc_for_id(id)
	dialog_box.visible = true
	grid_container.get_children().map(func(c): c.queue_free())
	var label = Label.new()
	label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	var npc_chat = ChatUtil.get_chat_for_id(npc_data["chatId"])
	label.text = npc_chat["titleList"].pick_random()
	grid_container.add_child(label)
	for i in npc_data["menuList"]:
		var btn = Button.new()
		btn.add_theme_color_override("font_color", ColorUtil.Color_33)
		btn.text = i["title"]
		btn.alignment = HORIZONTAL_ALIGNMENT_LEFT
		var empty_style = StyleBoxEmpty.new()
		btn.add_theme_stylebox_override("normal", empty_style)
		btn.add_theme_stylebox_override("hover", empty_style)
		btn.add_theme_stylebox_override("pressed", empty_style)
		btn.add_theme_stylebox_override("disabled", empty_style)
		btn.add_theme_stylebox_override("focus", empty_style)
		btn.pressed.connect(_on_any_child_pressed.bind(i))
		grid_container.add_child(btn)

func _on_dialog_box_gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
			if event.is_pressed() and event.button_index == MouseButton.MOUSE_BUTTON_RIGHT:
				dialog_box.visible = false

func _on_any_child_pressed(data: Dictionary):
	print("按钮被点击:", data)
	dialog_box.visible = false
	if 1.0 == data["type"]:
		for node in get_tree().get_nodes_in_group("door"):
			node.get_parent().remove_child(node)
			node.queue_free()
		var mapData = MapUtil.get_map_for_id(data["dest_id"])
		load_map_and_npc(mapData["id"])
		role.position = Vector2(data["dest_x"], data["dest_y"])
		position_label.text = mapData["name"] + "  [" + str(int(role.position.x / 20)) + "," + str(int(role.position.y / 20)) + "]"
	elif 2.0 == data["type"]:
		print('qqqqqqqqqqq')
		#fight.init_data('[{"position":0,"name":"刘明","skin":10900},{"position":1,"name":"朱明","skin":10900},{"position":2,"name":"杨萍军","skin":10900},{"position":3,"name":"李娟桂英","skin":10900},{"position":4,"name":"刘丽","skin":10900},{"position":5,"name":"黄敏毅","skin":10900},{"position":6,"name":"周毅建军","skin":10900},{"position":7,"name":"林勇丽","skin":10900},{"position":8,"name":"黄涛萍","skin":10900},{"position":9,"name":"赵洋","skin":10900}]','[{"id":1,"name":"马丽","skin":10900,"pet":{"name":"郭杰","skin":10900}},{"id":2,"name":"李玉兰","skin":10900,"pet":{"name":"李洋","skin":10900}},{"id":3,"name":"马静","skin":10900,"pet":{"name":"徐艳毅","skin":10900}},{"id":4,"name":"陈萍","skin":10900,"pet":{"name":"黄刚","skin":10900}},{"id":5,"name":"刘丽","skin":10900,"pet":{"name":"马静","skin":10900}}]')
		fight.init_data('[{"id":1,"tag":1,"position":0,"skin":10900,"name":"鬼王67","fullHp":77,"fullMp":14,"fullAp":69,"fullSp":67,"currentHp":77,"currentMp":14,"currentAp":69,"currentSp":67},{"id":2,"tag":1,"position":1,"skin":10900,"name":"鬼王33","fullHp":97,"fullMp":70,"fullAp":23,"fullSp":33,"currentHp":97,"currentMp":70,"currentAp":23,"currentSp":33},{"id":3,"tag":1,"position":2,"skin":10900,"name":"鬼王64","fullHp":48,"fullMp":65,"fullAp":23,"fullSp":64,"currentHp":48,"currentMp":65,"currentAp":23,"currentSp":64},{"id":4,"tag":1,"position":3,"skin":10900,"name":"鬼王49","fullHp":64,"fullMp":43,"fullAp":33,"fullSp":49,"currentHp":64,"currentMp":43,"currentAp":33,"currentSp":49},{"id":5,"tag":1,"position":4,"skin":10900,"name":"鬼王69","fullHp":53,"fullMp":40,"fullAp":28,"fullSp":69,"currentHp":53,"currentMp":40,"currentAp":28,"currentSp":69},{"id":6,"tag":1,"position":5,"skin":10900,"name":"鬼王64","fullHp":39,"fullMp":81,"fullAp":80,"fullSp":64,"currentHp":39,"currentMp":81,"currentAp":80,"currentSp":64},{"id":7,"tag":1,"position":6,"skin":10900,"name":"鬼王69","fullHp":36,"fullMp":100,"fullAp":54,"fullSp":69,"currentHp":36,"currentMp":100,"currentAp":54,"currentSp":69},{"id":8,"tag":1,"position":7,"skin":10900,"name":"鬼王36","fullHp":45,"fullMp":62,"fullAp":33,"fullSp":36,"currentHp":45,"currentMp":62,"currentAp":33,"currentSp":36},{"id":9,"tag":1,"position":8,"skin":10900,"name":"鬼王67","fullHp":88,"fullMp":37,"fullAp":22,"fullSp":67,"currentHp":88,"currentMp":37,"currentAp":22,"currentSp":67},{"id":10,"tag":1,"position":9,"skin":10900,"name":"鬼王27","fullHp":88,"fullMp":95,"fullAp":60,"fullSp":27,"currentHp":88,"currentMp":95,"currentAp":60,"currentSp":27},{"id":1,"tag":2,"position":17,"skin":10900,"name":"八神90","fullHp":45,"fullMp":32,"fullAp":91,"fullSp":90,"currentHp":45,"currentMp":32,"currentAp":91,"currentSp":90,"pet":{"id":1,"tag":3,"position":12,"skin":10900,"name":"召唤兽63","fullHp":85,"fullMp":54,"fullAp":35,"fullSp":63,"currentHp":85,"currentMp":54,"currentAp":35,"currentSp":63}}]')
		fight.visible = true
		background_map.visible = false
		role.visible = false
	else:
		print(data["title"])

func _hide_fight():
	fight.visible = false
	background_map.visible = true
	role.visible = true


func _on_texture_rect_4_gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.is_pressed() and event.button_index == MouseButton.MOUSE_BUTTON_LEFT:
			print('点击了头像')
			var texture = load("res://resource/ui/smsj/22781065.png")
			texture_rect_2.texture = texture
